package lueerror

import (
	"fmt"
	"net/http"
)

// LueError 自定义 error
type LueError interface {
	HttpStatus() int
	Code() string
	SendMail() bool
	Msg() string
	Error() string
}

type errInfo struct {
	httpStatus int    // http status
	code       string // 自定义错误code
	error      error  // 错误信息 for dev
	msg        string // 错误信息 for user
	sendMail   bool   // 是否发送邮件
}

// HttpStatus 获取http 状态值
func (le *errInfo) HttpStatus() int {
	return le.httpStatus
}

// Code 获取自定义 code
func (le *errInfo) Code() string {
	return le.code
}

// SendMail 是否发送 mail
func (le *errInfo) SendMail() bool {
	return le.sendMail
}

// Msg 获取错误信息, 前端可 msg
func (le *errInfo) Msg() string {
	return le.msg
}

// Error
func (le *errInfo) Error() string {
	return fmt.Sprintf("%+v", le.error)
}

func initError(err error, code, alert string, httpStatus int, sendMail bool) *errInfo {
	return &errInfo{error: err, msg: alert, code: code, httpStatus: httpStatus, sendMail: sendMail}
}

// Error 初始化错误信息
func Error(err error, code, alert string, httpCode int) LueError {
	return initError(err, code, alert, httpCode, false)
}

// ErrorWithMail 带邮件错误
func ErrorWithMail(err error, code, alert string, httpCode int) LueError {
	//err = errors.WithStack(err)
	return initError(err, code, alert, httpCode, true)
}

// ServerError 服务器错误
func ServerError(err error, code string) LueError {
	return ErrorWithMail(err, code, "服务器忙，请稍后再试！", http.StatusInternalServerError)
}
